package com.gxl.butt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gxl.butt.dto.bo.User;
import com.gxl.butt.service.IHardUserService;
import com.gxl.butt.utils.AccountCheckUtil;
import com.gxl.butt.utils.CommonUtil;
import com.gxl.butt.utils.HttpUtils;
import com.gxl.butt.utils.JSONUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.gxl.butt.value.ErrorCode.SUCCESS_CODE_ZERO;
import static com.gxl.butt.value.ErrorMsg.*;
import static com.gxl.butt.value.StaticValue.*;

@Api(value = "user operator",tags = "user operator")
@RestController
@RequestMapping(value = "/harduser/")
public class HardUserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Reference(interfaceClass = IHardUserService.class,timeout = 10000,check = false)
    private IHardUserService iHardUserService;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    /**
     * 判断用户是否登录
     * @return
     */
    @ApiOperation(value="是否登陆", notes="判断用户是否已经登陆")
    @RequestMapping(value = "/isLogin",method = RequestMethod.GET)
    public JSONObject isLogin() {

        JSONObject userJson = (JSONObject) request.getSession().getAttribute(USER_SESSION);
        if (userJson!=null){
            return JSONUtils.getRoot(0,USER_LOGIN,STR_IS_EMPTY);
        }else {
            return JSONUtils.getRoot(-1,USER_LOGOUT,STR_IS_EMPTY);
        }

    }



    /**
     * 用户注册
     * @param account
     * @param password
     * @param nickname
     * @return
     */
    @ApiOperation(value="注册用户", notes="注册用户")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public JSONObject register(String account, String password, String nickname, String idcard) {



        Pattern pAll1=Pattern.compile(REG_LOWER_LETTER);
        Matcher mAll1 = pAll1.matcher(account);
        if (account==null||STR_IS_EMPTY.equals(account)||!mAll1.matches()){
            return JSONUtils.getRoot(-1,ACCOUNT_FORMAT_ERROR,STR_IS_EMPTY);
        }

        Pattern pAll2=Pattern.compile(REG_MATH);
        Matcher mAll2 = pAll2.matcher(password);
        if (password==null||STR_IS_EMPTY.equals(password)||!mAll2.matches()){
            return JSONUtils.getRoot(-2,PASSWORD_FORMAT_ERROR,STR_IS_EMPTY);
        }
        if (nickname==null||STR_IS_EMPTY.equals(nickname)||nickname.length()>8){
            return JSONUtils.getRoot(-3,NICK_NAME_FORMAT_ERROR,STR_IS_EMPTY);
        }

        if (idcard==null||STR_IS_EMPTY.equals(idcard)|| !CommonUtil.isIdNum(idcard)){
            return JSONUtils.getRoot(-5,IDCARD_FORMAT_ERROR,STR_IS_EMPTY);
        }

        JSONObject jsonObject = iHardUserService.registerUser(account, password, nickname,idcard);

        Integer issus = jsonObject.getInteger(JSONUTIL_ERROR_CODE);
        String msg = jsonObject.getString(JSONUTIL_MSG);
        if (issus== -1 ){
            return JSONUtils.getRoot(-4,ACCOUNT_EXIST,STR_IS_EMPTY);
        }else if (issus==-2){
            return JSONUtils.getRoot(-6,IDCARD_BE_REGISTER,STR_IS_EMPTY);
        }

        logger.info(">>>>>>>>>>>>>>>>>>>>> register user info >>>>>>>>>>>>>>>>>>>>>" + jsonObject.toJSONString());

        return JSONUtils.getRoot(0,msg,STR_IS_EMPTY);
    }

    /**
     * 用户登录
     * 登陆类型：账号密码
     * @param account
     * @param password
     * @return
     */
    @ApiOperation(value="用户登陆", notes="用户登陆")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public JSONObject login(String account, String password) {


        if (!AccountCheckUtil.checkAccountAndPassword(account,password)){
            return JSONUtils.getRoot(-1,ACCOUNT_OR_PASSWORD_ERROR,STR_IS_EMPTY);
        }

        JSONObject jsonObject = null;
        jsonObject = iHardUserService.loginUser(account, password);


        int logincode = jsonObject.getInteger(JSONUTIL_ERROR_CODE);
        String msg = jsonObject.getString(JSONUTIL_MSG);
        if (logincode == 0){//登录成功

            JSONObject userjson = jsonObject.getJSONObject(JSONUTIL_DATA);

            request.getSession().setAttribute(USER_SESSION,userjson);
            request.getSession().setAttribute(USER_ID,userjson.getLong("id"));
            request.getSession().setMaxInactiveInterval(Integer.valueOf(String.valueOf(SESSION_USER_MAX_INACTIVE_INTERVAL)));

            logger.info(">>>>>>>>>> login user info >>>>>>>>>>>>>" + userjson);
            return JSONUtils.getRoot(0,msg,userjson);
        } else{
             logger.info(">>>>>>>>>>>>>>> 登录失败 >>>>>>>>>>>>>>>>>" + msg);
            return JSONUtils.getRoot(-3,msg,STR_IS_EMPTY);
        }

    }

    /**
     * 用户登录
     * 登陆类型：小程序
     * @param user
     * @return
     */
    @ApiOperation(value="用户小程序登陆", notes="用户小程序登陆")
    @RequestMapping(value = "/xcxlogin",method = RequestMethod.POST)
    public JSONObject xcxlogin(@RequestBody User user) {

        JSONObject result = iHardUserService.xcxLogin(user);
        Long uid = (Long) result.get(JSONUTIL_DATA);
//        System.out.println(" >>>>>>>> USER_ID >>>>>>> " + uid);
        return JSONUtils.getRoot(0,SUCCESS_MSG,STR_IS_EMPTY);

    }

    /**
     * 用户登出
     * @return
     */
    @ApiOperation(value="用户登出", notes="用户登出")
    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    public JSONObject logout() {

        request.getSession().removeAttribute(USER_SESSION);//注销指定key为HARD_USER的信息
        return JSONUtils.getRoot(0,USER_LOGOUT,STR_IS_EMPTY);

    }


    /**
     * 查询用户账号是否被注册
     * @param account
     * @return
     */
    @ApiOperation(value="账号检测", notes="检测账号是否被注册")
    @RequestMapping(value = "/checkAccount",method = RequestMethod.POST)
    public JSONObject checkAccount(String account) {

        if (!AccountCheckUtil.checkAccount(account)){
            return JSONUtils.getRoot(-1,ACCOUNT_FORMAT_ERROR,STR_IS_EMPTY);
        }

        JSONObject jsonObject = null;
        jsonObject = iHardUserService.checkAccount(account);
        int logincode = jsonObject.getInteger(JSONUTIL_ERROR_CODE);
        String msg = jsonObject.getString(JSONUTIL_MSG);
        if (logincode == 0){//账号可用
            return JSONUtils.getRoot(0,msg,STR_IS_EMPTY);
        } else{
            return JSONUtils.getRoot(-2,msg,STR_IS_EMPTY);
        }

    }
    /**
     * 获取最新登录的十个用户
     * @return
     */
    @ApiOperation(value="获取最新登录的十个用户", notes="获取最新登录的十个用户")
    @RequestMapping(value = "/getTenUser",method = RequestMethod.GET)
    public JSONObject getTenUser() {

        JSONObject str = iHardUserService.getTenUser();

        return str;

    }
    /**
     * 测试分布式是否可以返回list类型
     * @return
     */
    @ApiOperation(value="测试分布式是否可以返回list类型", notes="测试分布式是否可以返回list类型")
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public JSONObject test() {

        String str = iHardUserService.getTestBeanList();

        return JSONUtils.getRoot(SUCCESS_CODE_ZERO,SUCCESS_MSG,str);

    }



}
